<template>
  <div class="board-page">
    <!-- 加载状态 -->
    <div v-if="!isLoad" class="margin-top load loading text-l load-project"></div>
    
    <!-- 主要内容 -->
    <div v-if="isLoad" class="main">
      <!-- 搜索和筛选区域 -->
      <div class="search-header">
        <van-search 
          v-model="searchText" 
          placeholder="搜索表白内容"
          @search="onSearch"
        />
        <van-button 
          type="primary" 
          size="small" 
          @click="showMyMenu"
          class="my-btn"
        >
          <van-icon name="more-o" />我的
        </van-button>
      </div>

      <!-- 表白列表 -->
      <div class="list">
        <div 
          v-for="(item, index) in boardList" 
          :key="item.postId"
          class="item shadow-project"
          :class="`item-${(index % 6) + 1}`"
          @click="goToDetail(item.postId)"
        >
          <!-- 我的标记 -->
          <div v-if="nowUserId === item.userId" class="mark-mine bg-white">我的</div>

          <!-- 顶部内容 -->
          <div class="top">
            <img 
              :src="item.image || '/images/default-avatar.svg'" 
              class="left loading" 
              alt="头像"
            />
            <div class="right">
              <div class="title">
                <span class="name text-white text-bold">
                  TO: {{ item.title || '匿名表白' }}
                </span>
              </div>
              <div class="desc">
                <span>{{ item.content || '' }}</span>
              </div>

              <!-- 图片展示 -->
              <div v-if="hasImages(item)" class="pic">
                <img 
                  v-if="item.pic1"
                  :src="item.pic1"
                  :class="`loading img${getImageCount(item)}`"
                  @click="previewImage(item.pic1, getImageList(item))"
                  alt="表白图片"
                />
                <img 
                  v-if="item.pic2"
                  :src="item.pic2"
                  :class="`loading img${getImageCount(item)}`"
                  @click="previewImage(item.pic2, getImageList(item))"
                  alt="表白图片"
                />
                <img 
                  v-if="item.pic3"
                  :src="item.pic3"
                  :class="`loading img${getImageCount(item)}`"
                  @click="previewImage(item.pic3, getImageList(item))"
                  alt="表白图片"
                />
              </div>

              <!-- From信息 -->
              <div v-if="item.nickName" class="line1 text-white" style="opacity: .9;">
                From: {{ item.nickName }}
              </div>
              <div class="line2">{{ formatTime(item.createTimestamp) }}</div>
            </div>
          </div>

          <!-- 底部操作区 -->
          <div class="bottom">
            <div class="info">
              <div @click="toggleLike(item, index)">
                <van-icon :name="item.like > 0 ? 'good-job' : 'good-job-o'" :color="item.like > 0 ? '#fff' : '#fff'" />
                {{ item.likeNum || 0 }}
              </div>
              <div @click="goToComments(item.postId)">
                <van-icon name="chat-o" />
                {{ item.commentNum || 0 }}
              </div>
              <div @click="toggleFav(item, index)">
                <van-icon :name="item.fav > 0 ? 'star' : 'star-o'" :color="item.fav > 0 ? '#fff' : '#fff'" />
                {{ item.favNum || 0 }}
              </div>
            </div>
          </div>

          <!-- 操作按钮（仅自己的可见） -->
          <div v-if="nowUserId === item.userId" class="oprt">
            <div class="bg-pink light" @click="setStatus(item.postId)">
              <van-icon name="setting-o" />状态设定
            </div>
            <div class="bg-blue light" @click="editBoard(item.postId)">
              <van-icon name="edit" />编辑
            </div>
            <div class="bg-orange light" @click="deleteBoard(item.postId)">
              <van-icon name="delete-o" />删除
            </div>
          </div>
        </div>
      </div>

      <!-- 加载更多 -->
      <van-loading v-if="loading" class="loading-more">加载中...</van-loading>
      <div v-if="!hasMore && boardList.length > 0" class="no-more">没有更多了</div>
    </div>

    <!-- 发表按钮 -->
    <div class="post safe-bottom">
      <div class="inner shadow-project bg-pink" @click="addBoard">
        <van-icon name="like-o" />写表白
      </div>
    </div>

    <!-- 我的菜单 -->
    <van-action-sheet 
      v-model:show="showMyActionSheet" 
      :actions="myActions" 
      @select="onMyActionSelect"
    />

    <!-- 状态设定菜单 -->
    <van-action-sheet 
      v-model:show="showStatusActionSheet" 
      :actions="statusActions" 
      @select="onStatusActionSelect"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive, computed } from 'vue'
import { useRouter } from 'vue-router'
import { useAppStore } from '@/stores/app'
import { useUserStore } from '@/stores/user'
import { boardApi, type PostQuery } from '@/api/board'
import { showToast, showConfirmDialog, showImagePreview } from 'vant'

const router = useRouter()
const appStore = useAppStore()
const userStore = useUserStore()

// 设置页面标题
appStore.setTitle('表白墙')

// 响应式数据
const isLoad = ref(false)
const loading = ref(false)
const hasMore = ref(true)
const searchText = ref('')
const boardList = ref([])
const showMyActionSheet = ref(false)
const showStatusActionSheet = ref(false)
const currentStatusPostId = ref('')

// 当前用户ID
const nowUserId = computed(() => userStore.userInfo?.id || '')

// 分页参数
const pageParams = reactive({
  pageNo: 0,  // 从0开始
  pageSize: 10
})

// 我的操作菜单
const myActions = [
  { name: '我的表白', value: 'my' },
  { name: '我的点赞', value: 'like' },
  { name: '我的收藏', value: 'fav' }
]

// 状态设定菜单
const statusActions = [
  { name: '正常展示', value: 1 },
  { name: '仅自己可见', value: 0 }
]

// 加载表白列表
const loadBoardList = async (refresh = false) => {
  try {
    loading.value = true
    
    if (refresh) {
      pageParams.pageNo = 0  // 从0开始
      boardList.value = []
    }

    const params: PostQuery = {
      pageNo: pageParams.pageNo,
      pageSize: pageParams.pageSize,
      str: searchText.value,
      typeId: '1' // 表白墙类型ID
    }

    const response = await boardApi.getList(params)
    
    if (response.code === 1) {
      const newList = response.data || []
      
      if (refresh) {
        boardList.value = newList
      } else {
        boardList.value.push(...newList)
      }
      
      hasMore.value = newList.length === pageParams.pageSize
      pageParams.pageNo++
    } else {
      showToast(response.msg || '加载失败')
    }
  } catch (error: any) {
    console.error('加载表白列表失败:', error)
    if (error.message?.includes('401') || error.message?.includes('未授权')) {
      showToast('请先登录后查看')
    } else {
      showToast('网络错误，请检查服务器连接')
    }
  } finally {
    loading.value = false
    isLoad.value = true
  }
}

// 搜索
const onSearch = () => {
  loadBoardList(true)
}

// 显示我的菜单
const showMyMenu = () => {
  showMyActionSheet.value = true
}

// 我的菜单选择
const onMyActionSelect = (action: any) => {
  showMyActionSheet.value = false
  console.log('选择了:', action.name)
  // TODO: 实现筛选逻辑
}

// 状态设定
const setStatus = (postId: string) => {
  currentStatusPostId.value = postId
  showStatusActionSheet.value = true
}

// 状态设定选择
const onStatusActionSelect = async (action: any) => {
  showStatusActionSheet.value = false
  try {
    // TODO: 调用状态设定API
    showToast(`已设置为${action.name}`)
  } catch (error) {
    console.error('状态设定失败:', error)
    showToast('设定失败')
  }
}

// 点赞/取消点赞
const toggleLike = async (item: any, index: number) => {
  try {
    if (item.like > 0) {
      await boardApi.dislike(item.postId)
      boardList.value[index].like = 0
      boardList.value[index].likeNum = Math.max(0, (item.likeNum || 0) - 1)
    } else {
      await boardApi.like(item.postId)
      boardList.value[index].like = 1
      boardList.value[index].likeNum = (item.likeNum || 0) + 1
    }
  } catch (error) {
    console.error('点赞操作失败:', error)
    showToast('操作失败')
  }
}

// 收藏/取消收藏
const toggleFav = async (item: any, index: number) => {
  try {
    // TODO: 实现收藏API调用
    if (item.fav > 0) {
      boardList.value[index].fav = 0
      boardList.value[index].favNum = Math.max(0, (item.favNum || 0) - 1)
    } else {
      boardList.value[index].fav = 1
      boardList.value[index].favNum = (item.favNum || 0) + 1
    }
    showToast(item.fav > 0 ? '已收藏' : '已取消收藏')
  } catch (error) {
    console.error('收藏操作失败:', error)
    showToast('操作失败')
  }
}

// 跳转到评论页面
const goToComments = (postId: string) => {
  router.push(`/comment?id=${postId}&type=post`)
}

// 预览图片
const previewImage = (current: string, images: string[]) => {
  showImagePreview({
    images,
    startPosition: images.indexOf(current)
  })
}

// 检查是否有图片
const hasImages = (item: any) => {
  return item.pic1 || item.pic2 || item.pic3
}

// 获取图片数量
const getImageCount = (item: any) => {
  let count = 0
  if (item.pic1) count++
  if (item.pic2) count++
  if (item.pic3) count++
  return count
}

// 获取图片列表
const getImageList = (item: any) => {
  const images = []
  if (item.pic1) images.push(item.pic1)
  if (item.pic2) images.push(item.pic2)
  if (item.pic3) images.push(item.pic3)
  return images
}

// 编辑表白
const editBoard = (postId: string) => {
  router.push(`/board/edit?id=${postId}`)
}

// 删除表白
const deleteBoard = async (postId: string) => {
  try {
    await showConfirmDialog({
      title: '确认删除',
      message: '确定要删除这条表白吗？'
    })
    
    const response = await boardApi.delete(postId)
    if (response.code === 1) {
      showToast('删除成功')
      loadBoardList(true)
    } else {
      showToast(response.msg || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      showToast('删除失败')
    }
  }
}

// 添加表白
const addBoard = () => {
  router.push('/board/add')
}

// 跳转到详情页
const goToDetail = (postId: string) => {
  router.push(`/board/${postId}`)
}

// 格式化时间
const formatTime = (timestamp: string | number) => {
  if (!timestamp) return ''
  const date = new Date(typeof timestamp === 'string' ? parseInt(timestamp) * 1000 : timestamp * 1000)
  return date.toLocaleString()
}

// 页面加载
onMounted(() => {
  loadBoardList(true)
})
</script>

<style scoped>
.board-page {
  background-color: #f8f8f8;
  min-height: 100vh;
  padding-bottom: 80px;
}

.search-header {
  display: flex;
  align-items: center;
  padding: 10px;
  background: white;
  gap: 10px;
}

.my-btn {
  flex-shrink: 0;
}

.list {
  width: 100%;
  display: flex;
  flex-direction: column;
  padding: 12.5px;
}

.list .item {
  width: 100%;
  display: flex;
  flex-direction: column;
  padding: 0;
  background-color: #fff;
  margin-bottom: 15px;
  align-items: flex-start;
  border-radius: 10px;
  position: relative;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

/* 彩色背景 - 完全按照原项目样式 */
.list .item.item-1 { background-color: #F6B7B5; }
.list .item.item-2 { background-color: #ECBB9A; }
.list .item.item-3 { background-color: #2980B9; }
.list .item.item-4 { background-color: #C29CD2; }
.list .item.item-5 { background-color: #73C6B5; }
.list .item.item-6 { background-color: #F5DF6A; }

.list .item .mark-mine {
  position: absolute;
  bottom: 0;
  left: 0;
  font-size: 12px;
  padding: 3px 8px;
  border-bottom-left-radius: inherit;
  border-top-right-radius: 10px;
  background-color: white;
  color: #333;
}

.list .top {
  width: 100%;
  padding: 12.5px;
  display: flex;
}

.list .bottom {
  width: 100%;
  padding: 7.5px 12.5px;
  border-top: 1px solid rgba(255, 255, 255, 0.1);
  display: flex;
}

.list .bottom .info {
  width: 100%;
  display: flex;
  justify-content: space-around;
}

.list .bottom .info > div {
  width: 33.33%;
  border-right: 1px dotted rgba(255, 255, 255, 0.3);
  text-align: center;
  font-size: 12px;
  color: #fff;
  cursor: pointer;
}

.list .bottom .info > div:last-child {
  border-right: 0;
}

.list .left {
  width: 30px;
  height: 30px;
  border-radius: 50%;
  margin-right: 5px;
  object-fit: cover;
}

.list .right {
  flex: 1;
  display: flex;
  flex-direction: column;
  padding: 3px 5px;
}

.list .right .title {
  display: flex;
  padding: 0;
  justify-content: space-between;
  align-items: center;
  margin-top: 2px;
  z-index: 9;
}

.list .right .title .name {
  font-size: 14px;
  color: #fff;
  font-weight: bold;
}

.list .right .desc {
  margin-top: 12.5px;
  width: 100%;
  display: flex;
  font-size: 13px;
  line-height: 1.3;
  color: #fff;
}

.list .right .pic {
  margin-top: 10px;
  width: 100%;
  display: flex;
  flex-wrap: wrap;
}

.list .right .pic img {
  height: 85px;
  width: 85px;
  margin-right: 5px;
  margin-bottom: 5px;
  border-radius: 5px;
  object-fit: cover;
  cursor: pointer;
}

.list .right .pic img.img1 {
  height: 115px;
  width: 115px;
}

.list .right .line1 {
  width: 100%;
  font-size: 12px;
  color: #fff;
  margin-top: 8px;
}

.list .right .line2 {
  width: 100%;
  text-align: right;
  padding: 0;
  font-size: 11px;
  color: #fff;
  opacity: 0.6;
  margin-top: 10px;
}

.list .oprt {
  width: 100%;
  display: flex;
  justify-content: flex-end;
  padding: 2.5px 0;
  margin-top: -5px;
  margin-bottom: 25px;
}

.list .oprt > div {
  padding: 4px 10px;
  font-size: 12px;
  background-color: #f2f2f2;
  margin-right: 8px;
  border-radius: 4px;
  cursor: pointer;
}

.list .oprt > div:last-child {
  margin-right: 2px;
}

.post {
  width: 100%;
  position: fixed;
  left: 15px;
  bottom: 40px;
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 999;
}

.post > div {
  font-size: 16px;
  background-color: #e91e63;
  color: #fff;
  padding: 8px 80px;
  border-radius: 20px;
  cursor: pointer;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
}

.loading-more {
  text-align: center;
  padding: 20px;
}

.no-more {
  text-align: center;
  padding: 20px;
  color: #999;
  font-size: 14px;
}

/* 工具类 */
.text-white { color: white; }
.text-bold { font-weight: bold; }
.bg-white { background-color: white; }
.bg-pink { background-color: #e91e63; }
.bg-blue { background-color: #2196f3; }
.bg-orange { background-color: #ff9800; }
.light { opacity: 0.9; }
.shadow-project { box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1); }
</style>